package com.kaoshi.management.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.kaoshi.management.service.FileUploadService;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadServicelmpl implements FileUploadService {

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.keyId}")
    private String keyid;
    @Value("${aliyun.keySecret}")
    private String keysecret;
    @Value("${aliyun.bucketName}")
    private String buncket;

    @Override
    public String uploadFile(MultipartFile file) {
        String url = "";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
        try {
            // 创建PutObjectRequest对象。
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            String replace = UUID.randomUUID().toString().replace("-", "");
            originalFilename = replace + originalFilename;
            String time = new DateTime().toString("yyyy/MM/dd");
            originalFilename = time + "/" + originalFilename;

            PutObjectResult putObjectResult = ossClient.putObject(buncket, originalFilename, inputStream);

            url = "https://" + buncket + "." + endpoint + "/" + originalFilename;
        } catch (Exception ce) {
            System.out.println("上传异常--");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
